import turtle
import math

# 设置屏幕
screen = turtle.Screen()
screen.setup(800, 800)
screen.title("鳄鱼追人")

# 定义等边三角形边长
side_length = 400
height = math.sqrt(3) / 2 * side_length

# 定义人
person = turtle.Turtle()
person.shape("circle")
person.color("blue")
person.speed(0)
# 人的初始位置在等边三角形中心
person.penup()
person.goto(0, -height / 3)
person.pendown()
person.speed = 10

# 定义三只鳄鱼
crocodiles = []
speeds = [20.5, 20, 15]
angles = [90, 210, 330]
croc_positions = []
for i in range(3):
    croc = turtle.Turtle()
    croc.shape("triangle")
    croc.color("green")
    croc.speed(0)
    angle = math.radians(angles[i])
    x = side_length / 2 * math.cos(angle)
    y = side_length / 2 * math.sin(angle)
    croc_positions.append((x, y))
    croc.penup()
    croc.goto(x, y)
    croc.pendown()
    croc.speed = speeds[i]
    crocodiles.append(croc)

# 绘制由三只鳄鱼初始位置连线而成的等边三角形
triangle = turtle.Turtle()
triangle.speed(0)
triangle.penup()
triangle.goto(*croc_positions[0])
triangle.pendown()
for pos in croc_positions[1:] + [croc_positions[0]]:
    triangle.goto(*pos)
triangle.hideturtle()


def calculate_distance(t1, t2):
    x1, y1 = t1.position()
    x2, y2 = t2.position()
    return math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)


def move_person():
    # 计算人到三只鳄鱼的向量和
    vector_sum_x = 0
    vector_sum_y = 0
    for croc in crocodiles:
        dx = croc.xcor() - person.xcor()
        dy = croc.ycor() - person.ycor()
        vector_sum_x += dx
        vector_sum_y += dy

    # 计算向量和的角度
    angle = math.atan2(vector_sum_y, vector_sum_x) + math.pi
    person.setheading(math.degrees(angle))

    # 移动人
    person.forward(person.speed)


def move_crocodiles():
    for croc in crocodiles:
        # 计算鳄鱼到人的角度
        dx = person.xcor() - croc.xcor()
        dy = person.ycor() - croc.ycor()
        angle = math.atan2(dy, dx)
        croc.setheading(math.degrees(angle))
        # 移动鳄鱼
        croc.forward(croc.speed)


def game_loop():
    move_person()
    move_crocodiles()

    # 检查是否有鳄鱼追到了人
    for croc in crocodiles:
        if calculate_distance(person, croc) < 10:
            print("人被抓住了！")
            screen.bye()
            return

    screen.ontimer(game_loop, 100)


# 开始游戏循环
game_loop()

# 保持窗口打开
turtle.done()